package handler

import (
	"context"
	"encoding/json"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
	"mxshop_srvs/goods_srv/global"
	"mxshop_srvs/goods_srv/model"
	"mxshop_srvs/goods_srv/proto"
)

// Category商品分类

func (svc *GoodsServer) GetAllCategorysList(ctx context.Context, empty *emptypb.Empty) (*proto.CategoryListResponse, error) {
	/**
		[{
			//一级类目
			"id":xxx,
			"name":"",
			"level":1,
			"is_tab":false,
			"parent":12xxx,
			"sub_category":[  //二级类目
				"id":xxx,
				....
				"sub_category":[ //三级级类目
					...
						]
				]
			}
	]
	*/
	var categories []model.Category
	//预加载
	global.DB.Where(&model.Category{Level: 1}).Preload("SubCategory.SubCategory").Find(&categories)
	b, _ := json.Marshal(&categories)
	//返回json
	return &proto.CategoryListResponse{
		JsonData: string(b),
	}, nil

}

// GetSubCategory 获取子分类
func (svc *GoodsServer) GetSubCategory(ctx context.Context, request *proto.CategoryListRequest) (*proto.SubCategoryListResponse, error) {
	categoryListResponse := proto.SubCategoryListResponse{}
	var subCategoriesResp []*proto.CategoryInfoResponse
	var category model.Category
	var subCategoriesOrigin []model.Category
	//1. 校验分类
	if result := global.DB.First(&category, request.Id); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "商品分类不存在!")
	}
	categoryListResponse.Info = &proto.CategoryInfoResponse{
		Id:             category.ID,
		Name:           category.Name,
		Level:          category.Level,
		IsTab:          category.IsTab,
		ParentCategory: category.ParentCategoryID,
	}

	preloads := "SubCategory"
	if category.Level == 1 {
		preloads = "SubCategory.SubCategory"
	}
	global.DB.Where(&model.Category{ParentCategoryID: request.Id}).Preload(preloads).Find(&subCategoriesOrigin)
	for _, sub := range subCategoriesOrigin {
		subCategoriesResp = append(subCategoriesResp, &proto.CategoryInfoResponse{
			Id:             sub.ID,
			Name:           sub.Name,
			Level:          sub.Level,
			IsTab:          sub.IsTab,
			ParentCategory: sub.ParentCategoryID,
		})
	}
	categoryListResponse.SubCategorys = subCategoriesResp
	return &categoryListResponse, nil
}

func (svc *GoodsServer) CreateCategory(ctx context.Context, request *proto.CategoryInfoRequest) (*proto.CategoryInfoResponse, error) {
	category := &model.Category{
		Name:  request.Name,
		Level: request.Level,
	}
	if request.Level != 1 {
		//查询父类目是否存在
		category.ParentCategoryID = request.ParentCategory
	}
	category.IsTab = request.IsTab
	global.DB.Save(category)
	return &proto.CategoryInfoResponse{Id: category.ID}, nil
}

func (svc *GoodsServer) DeleteCategory(ctx context.Context, request *proto.DeleteCategoryRequest) (*emptypb.Empty, error) {
	if result := global.DB.Delete(&model.Category{}, request.Id); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "商品分类不存在!")
	}
	return &emptypb.Empty{}, nil
}

func (svc *GoodsServer) UpdateCategory(ctx context.Context, request *proto.CategoryInfoRequest) (*emptypb.Empty, error) {
	category := &model.Category{}

	if result := global.DB.First(category, request.Id); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "商品分类不存在!")
	}
	if request.Name != "" {
		category.Name = request.Name
	}
	if request.ParentCategory != 0 {
		category.ParentCategoryID = request.ParentCategory
	}

	if request.Level != 0 {
		category.Level = request.Level
	}

	global.DB.Save(category)
	return &emptypb.Empty{}, nil
}
